var app = new Vue({
  el: "#app",
  data: {
    map: null,
    markerList: [],
    showDetail: false,
    dataList: [],
    level: "province", // 数据级别 province: 省级 city: 市级 enterprise: 企业
    // level: "enterprise", // 数据级别 province: 省级 city: 市级 enterprise: 企业
    provinceLevel: 5, // 省级数据级别
    cityLevel: 7, // 市级数据级别
    enterpriseLevel: 9, // 企业数据级别
    timer: null, // 定时器
    userLocation: [116.39, 39.9], // 用户位置 [经度, 纬度] 默认值 北京
    keyword: "", // 搜索关键词
    searchResult: [], // 搜索结果
    detailInfo: {}, // 详情信息
    loadingDetail: false, // 加载详情
    showDialog: false, // 显示弹窗
    form: {
      name: "", // 姓名
      phone: "", // 手机号
    },
    rules: {
      name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
      phone: [
        { required: true, message: "请输入联系电话", trigger: "blur" },
        {
          pattern:
            /^(?:(?:\+?86)?1[3-9]\d{9})$|^(?:(?:\d{3,4}-)?\d{7,8}(?:-\d{1,6})?)$/,
          message: "联系电话格式不正确",
          trigger: "blur",
        },
      ],
    },
    loadingSubmit: false, // 提交中
    markerZindexCopy: 1,
    activeMarketId: "", // 当前标记id
    activeMarket: null, // 当前标记id
    showButton: false, // 显示按钮
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = new AMap.Map("mapContainer", {
        resizeEnable: true,
        zoom: this.provinceLevel,
        // center: [106, 35], // 中心点 北京
        // zoom: this.enterpriseLevel,
        // center: [114.4839, 38.0353],  // 中心点 石家庄
      });
      // 在初始化地图时，如果center属性缺省，地图默认定位到用户所在城市的中心
      this.userLocation = [this.map.getCenter().lng, this.map.getCenter().lat];
      this.map.on("zoomchange", this.mapZoom);
      this.map.on("mapmove", this.mapMove);
      const _this = this;
      //异步加载控件
      AMap.plugin("AMap.ToolBar", function () {
        var toolbar = new AMap.ToolBar({
          position: "LT",
        }); //缩放工具条实例化
        _this.map.addControl(toolbar); //添加控件
      });

      this.$nextTick(() => {
        document.querySelector(".amap-logo").style.opacity = 0; // 隐藏高德logo
        document.querySelector(".amap-copyright").style.opacity = 0; // 隐藏高德logo
        this.getInfo();
      });
    },
    // 获取信息
    getInfo() {
      apiGetInfo()
        .then((res) => {
          const { data } = res;
          if (data) {
            data.enterprise = data.enterprise.filter((item) => {
              return item.pos.length > 0;
            });
            data.enterprise.forEach((item) => {
              item.distance = this.getDistance(item.pos);
            });
            console.log(data);
            this.dataList = data;
            if (parseInt(data.is_join) === 0) {
              this.showButton = true;
            }
            this.setMarker();
            this.onSearch();
          }
        })
        .catch((err) => {
          this.$message.error((err && err.msg) || err);
        });
    },
    // 设置标记
    setMarker() {
      this.map.remove(this.markerList);
      this.markerList = [];
      if (this.level === "enterprise") {
        const bounds = this.map.getBounds();
        const southWest = bounds.getSouthWest(); // 左下角
        const northEast = bounds.getNorthEast(); // 右上角
        const add = 0.05;
        this.dataList.enterprise.forEach((item) => {
          const { id, name, pos } = item;
          if (
            pos[0] < southWest.lng - add ||
            pos[0] > northEast.lng + add ||
            pos[1] < southWest.lat - add ||
            pos[1] > northEast.lat + add
          ) {
            return;
          }
          const marker = new AMap.Marker({
            position: new AMap.LngLat(pos[0], pos[1]),
            content: `<div class="map-marker-box1"  data-id="${id}">
               <div class="map-marker-pos"></div>
               <i class="map-marker-icon"></i>
               <div class="map-marker-title"> ${name}</div>
             </div>`,
            offset: new AMap.Pixel(-100, -45),
            extData: { id },
          });
          if (this.activeMarketId === id) {
            this.setActiveMarket(marker);
          }
          marker.on("click", this.onMarkerClick);
          marker.on("mouseover", this.onMarkerMouseover);
          marker.on("mouseout", this.onMarkerMouseout);
          this.markerList.push(marker);
        });
      } else {
        this.dataList[this.level].forEach((item) => {
          const { name, pos, value } = item;
          const marker = new AMap.Marker({
            position: new AMap.LngLat(pos[0], pos[1]),
            content: `<div class="map-marker-box">
              <div class="map-marker-content">
                <div class="map-marker-title">${name}</div>
                <div class="map-marker-value">${value}</div>
              </div>
            </div>`,
            offset: new AMap.Pixel(-24, -50),
          });
          marker.on("click", this.onMarkerClick);
          this.markerList.push(marker);
        });
      }
      this.map.add(this.markerList);
    },
    // 地图缩放
    mapZoom() {
      if (this.map.getZoom() < this.cityLevel) {
        // 显示省级数据
        if (this.level !== "province") {
          this.level = "province";
          this.setMarker();
        }
      } else if (
        this.map.getZoom() >= this.cityLevel &&
        this.map.getZoom() < this.enterpriseLevel
      ) {
        // 显示市级数据
        if (this.level !== "city") {
          this.level = "city";
          this.setMarker();
        }
      } else if (this.map.getZoom() >= this.enterpriseLevel) {
        // 显示企业名称
        if (this.level !== "enterprise") {
          this.level = "enterprise";
          this.setMarker();
        }
      }
    },
    // 地图移动
    mapMove() {
      if (this.timer) {
        return;
      }
      if (this.level === "enterprise") {
        this.setMarker();
      }
    },
    // 点击标记
    onMarkerClick(e) {
      if (this.level === "province") {
        this.map.setZoomAndCenter(this.cityLevel, e.lnglat, false, 800);
      } else if (this.level === "city") {
        this.map.setZoomAndCenter(this.enterpriseLevel, e.lnglat, false, 800);
      } else if (this.level === "enterprise") {
        this.map.setCenter(e.lnglat, false, 100);
        const id = e.target.getExtData().id;
        this.setActiveMarket(e.target);
        this.getDetail(id);
        this.showDetail = false;
        setTimeout(() => {
          this.showDetail = true;
        }, 300);
      }
    },
    // 设置当前标记
    setActiveMarket(marker) {
      if (this.activeMarket) {
        this.activeMarket.setzIndex(12);
        this.activeMarket.setContent(
          this.activeMarket
            .getContent()
            .replace(
              "map-marker-box1 map-marker-box1-active",
              "map-marker-box1"
            )
        );
      }
      this.activeMarket = marker;
      this.activeMarket.setzIndex(100);
      this.activeMarket.setContent(
        this.activeMarket
          .getContent()
          .replace("map-marker-box1", "map-marker-box1 map-marker-box1-active")
      );
      this.activeMarketId = this.activeMarket.getExtData().id;
    },
    // 鼠标移入标记
    onMarkerMouseover(e) {
      this.markerZindexCopy = e.target.getzIndex();
      e.target.setzIndex(100);
    },
    // 鼠标移出标记
    onMarkerMouseout(e) {
      e.target.setzIndex(this.markerZindexCopy);
    },
    // 点击企业
    onCompanyClick(item) {
      this.activeMarketId = item.id;
      this.level = "enterprise";
      this.map.setZoomAndCenter(
        this.enterpriseLevel,
        new AMap.LngLat(item.pos[0] + 0.3, item.pos[1]),
        false,
        100
      );
      this.getDetail(item.id);
      this.showDetail = false;
      setTimeout(() => {
        this.showDetail = true;
      }, 300);
    },
    // 获取企业详情
    getDetail(id) {
      this.loadingDetail = true;
      apiGetDetail({ id })
        .then((res) => {
          const { data } = res;
          if (data) {
            this.detailInfo = data;
          }
          this.loadingDetail = false;
        })
        .catch((err) => {
          this.$message.error((err && err.msg) || err);
          this.loadingDetail = false;
        });
    },
    // 两个经纬度之间的距离
    getDistance(pos) {
      let distance = AMap.GeometryUtil.distance(this.userLocation, pos) / 1000; // 计算出的是两点的距离，单位为米
      distance = Math.round(distance * 10) / 10; // 保留小数1位
      return distance;
    },
    // 搜索
    onSearch() {
      this.searchResult = [];
      if (this.keyword === "") {
        this.searchResult = this.dataList.enterprise.filter((item) => {
          return this.dataList.recommend.indexOf(item.id) > -1;
        });
      } else {
        this.searchResult = this.dataList.enterprise.filter((item) => {
          return item.name.indexOf(this.keyword) > -1;
        });
      }
      this.searchResult.sort((a, b) => {
        return a.distance - b.distance;
      });
    },
    // 申请入驻
    onApply() {
      this.showDialog = true;
    },
    // 联系人去掉开头和结尾的空格
    onChange() {
      this.form.name = this.form.name.trim();
    },
    // 提交申请
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loadingSubmit = true;
          apiSubmit(this.form)
            .then((res) => {
              this.$message.success("提交成功");
              setTimeout(() => {
                this.showDialog = false;
                this.loadingSubmit = false;
              }, 1000);
            })
            .catch((err) => {
              this.$message.error((err && err.msg) || err);
              this.loadingSubmit = false;
            });
        }
      });
    },
  },
});
